package com.freewater.springboot.demo.validation;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.hibernate.validator.HibernateValidator;

import java.util.Set;

public class ValidatorUtil {

    private static final Validator validator;
    private static final ValidatorFactory validatorFactory;

    static {
        /* 使用hibernate的注解来进行验证 failFast true仅仅返回第一条错误信息 false返回所有错误 */
        validatorFactory = Validation
                .byProvider(HibernateValidator.class).configure()
                .failFast(false)
                .buildValidatorFactory();
        validator = validatorFactory.getValidator();
    }

    public static void closeFactory() {
        validatorFactory.close();
    }

    /**
     * 校验对象
     */
    public static <T> Set<ConstraintViolation<T>> validate(T obj, Class<?>... groupClasses) {
        final Set<ConstraintViolation<T>> constraintViolations;
        if (groupClasses != null && groupClasses.length > 0) {
            constraintViolations = validator.validate(obj, groupClasses);
        } else {
            constraintViolations = validator.validate(obj);
        }
        return constraintViolations;
    }
}
